import { ActivatedRoute } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { DFormGroupRuleDirective, DValidateRules, DValidators, FormLayout } from 'ng-devui/form';
import { of } from 'rxjs';
import { delay, map } from 'rxjs/operators';
import { web_existUsernames, web_genders, web_hobbys, web_motives, web_msgs, web_characters } from '@/app/viewkit/web-questionnaire/formdata';
import { web_checkName, web_selectHobby, web_showToast } from '@/app/viewkit/web-questionnaire/validators';
import { downloadPdf } from "@/utils/loadPdf";

@Component({
  selector: 'app-web-questionnaire',
  templateUrl: './web-questionnaire.component.html',
  styleUrls: ['./web-questionnaire.component.scss']
})
export class WebQuestionnaireComponent implements OnInit {
  // 表单的布局方式
  layoutDirection: FormLayout = FormLayout.Horizontal;

  // 数据模型
  formData = JSON.parse(window.localStorage.getItem('webqn') ?? "false") || {
    // 页面进入前就输入好了，但是用户还可以二次修改
    username: '',
    gender: "",
    age: "",
    weChat: "",
    // 选择的
    motive: null,// 动机
    hobby: null, // 爱好
    character: null, // 性格
    // 输入的
    letter: null, // 字母个数
    number_p_n: ""
  };
  // 过滤姓名名单
  existUsernames = web_existUsernames;
  // 性别列表
  genders = web_genders
  // 动机数据
  motives = web_motives;
  // 爱好的options数据
  hobbys = web_hobbys;
  // 性格特点
  characters = web_characters;
  // 表单的非强制类型表单数据
  userFormGroup = new UntypedFormGroup({
    username: new UntypedFormControl(this.formData.username),
    gender: new UntypedFormControl(this.formData.gender),
    age: new UntypedFormControl(this.formData.age),
    weChat: new UntypedFormControl(this.formData.weChat),
    motive: new UntypedFormControl(this.formData.motive),
    hobby: new UntypedFormControl(this.formData.hobby),
    character: new UntypedFormControl(this.formData.character),
    letter: new UntypedFormControl(this.formData.letter),
    number_p_n: new UntypedFormControl(this.formData.number_p_n),
  });
  // 校验规则
  formRules: { [key: string]: DValidateRules } = {
    rule: { message: '表单未能通过校验，请检查是否有遗漏项.' },
    usernameRules: {
      validators: [
        { required: true },
        { minlength: 2 },
        { maxlength: 13 }
      ],
      asyncValidators: [{ sameName: web_checkName.bind(this), message: '姓名重复.' }],
    },
    genderRules: {
      validators: [
        { required: true }
      ]
    },
    ageRules: {
      validators: [
        { required: true },
        { max: 35, message: "兄弟，35岁考虑点别的吧" },
        { min: 18, message: "等成年后再来吧" }
      ]
    },
    weChatRules: {
      validators: [
        { required: true },
        { maxlength: 20, message: "我认为微信号没有超过20位的" },
        { minlength: 3, message: "我认为微信号没有低过3位的" },
      ]
    },
    motiveRules: {
      validators: [
        { required: true }
      ]
    },
    hobbyRules: {
      validators: [{ required: true }, { maxUser: web_selectHobby.bind(this), message: '选择不能超过3个' }],
    },
    characterRules: {
      validators: [
        { required: true }
      ]
    },
    letterRules: {
      validators: [
        { required: true },
        { integer: DValidators.integer, isNgValidator: true, message: "必须是数字哦" }
      ]
    },
    number_p_nRules: {
      validators: [
        { required: true },
        { minlength: 3, message: "至少也的是不知道三个字哈" },
        { maxlength: 140, message: "说的太多了，我有点无法处理" }
      ]
    }
  };

  constructor(private routerInfo: ActivatedRoute) { }
  ngOnInit(): void {
    this.routerInfo.data.subscribe(({ getData }: any) => {
      this.formData.username = getData.username;
      this.formData.weChat = getData.weChat;
      this.formData.age = getData.age;
      this.formData.gender = getData.gender;
      this.userFormGroup.get('username')?.setValue(getData.username)
      this.userFormGroup.get('gender')?.setValue(getData.gender)
      this.userFormGroup.get('age')?.setValue(getData.age)
      this.userFormGroup.get('weChat')?.setValue(getData.weChat)
    })
    // 监听表单事件，数据回填
    this.userFormGroup.valueChanges.subscribe((val) => {
      window.localStorage.setItem('webqn', JSON.stringify(val))
      this.formData = val;
    });
  }
  // 获取表单dom
  @ViewChild('userForm')
  userFormDir!: DFormGroupRuleDirective;
  // 信息队列
  msgs = web_msgs;
  // 提交
  submitForm({ valid, directive, data, errors }: any, webQN: any) {
    // console.log('Valid:', valid, 'Directive:', directive, 'data', data, 'errors', errors);
    // do something for submitting
    if (this.userFormDir.isReady) {
      console.log(this.formData);
      of(this.formData)
        .pipe(
          map((val) => 'success'),
          delay(100)
        )
        .subscribe((res) => {
          if (res === 'success') {
            this.showToast('success', '成功！', '请将保存的pdf文件发送给我，我的微信web_songyu.');
            downloadPdf(webQN, this.formData.username + '的前端测试', 1.2, 1.2)
            // this.showToast('success', '成功！', '您的选择已经提交，2个工作日内会把结果发送至您的邮箱或微信.');
          }
        });
    } else {
      this.showToast('error', '抱歉！', '您有必填项尚未完成答选');
    }
  }
  // 显示错误信息
  showToast = web_showToast.bind(this)
}
// 初始化时用户必填的数据字段
export class WebQN_UserInfo {
  constructor(public username: string, public weChat: string, public age: string, public gender: string) { }
}
